package tk.jfree.example.solr.api;

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.jfree.example.solr.api.service.ArticleQueryRepository;
import tk.jfree.example.solr.api.service.ArticleRepository;
import tk.jfree.example.solr.model.Article;
import tk.jfree.example.solr.model.ArticleForm;
import tk.jfree.example.solr.model.Query;
import tk.jfree.example.solr.model.Response;

/**
 * @author Cheng.Wei
 * @date 2019/04/28 23:13
 */
@Api
@RestController
@RequestMapping(value = "solr")
public class SolrController {
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private ArticleQueryRepository articleQueryRepository;

    @PostMapping
    public Response add(ArticleForm articleForm){
        Article article = new Article();
        article.setId(System.currentTimeMillis());
        article.setTitle(articleForm.getTitle());
        article.setAuthor(articleForm.getAuthor());
        article.setContent(articleForm.getContent());
        articleRepository.save(article);
        return Response.builder().data(article).build();
    }

    @PutMapping("/{id}")
    public Response update(@PathVariable long id,  ArticleForm articleForm){
        Article article = new Article();
        article.setId(id);
        article.setTitle(articleForm.getTitle());
        article.setAuthor(articleForm.getAuthor());
        article.setContent(articleForm.getContent());
        articleRepository.save(article);
        return Response.builder().data(article).build();
    }

    @GetMapping("/{id}")
    public Response get(@PathVariable long id){
        Article article = articleRepository.findById(id).orElseThrow(()->new RuntimeException("不存在"));
        return Response.builder().data(article).build();
    }

    @DeleteMapping("/{id}")
    public Response delete(@PathVariable long id){
        articleRepository.deleteById(id);
        return Response.builder().build();
    }

    @GetMapping
    public Response query(Query query){
        return Response.builder().data(articleQueryRepository.query(query)).build();
    }

}
